package org.zhs.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zhs.constants.SessionKeyConstants;
import org.zhs.util.MessageUtils;

import javax.servlet.http.HttpSession;
import java.util.Objects;

@Controller
public class Login {

    @Autowired
    private MessageSource messageSource;

    @RequestMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model model,
                        HttpSession session) {
        String languageKey =
                (String) session.getAttribute(SessionKeyConstants.LANGUAGE_KEY);
        if (!StringUtils.isEmpty(username) && Objects.equals(password, "123456")) {
//            添加session,用于拦截器验证
            session.setAttribute("loginUser",username);
            if(languageKey!=null){
                model.addAttribute("l",languageKey);
            }
//            设置重定向,因为已经在Diymvc中配置过这个main.html,所以直接访问main就可以重定向到dashboard
            return "redirect:/main.html";
        } else {
            String tipMessage = MessageUtils.getTipMessage("login.fail.message",languageKey);
            model.addAttribute("msg",tipMessage);
            if(languageKey!=null){
                model.addAttribute("l",languageKey);
            }
            return "redirect:index";
        }
    }
}
